#!/bin/sh

. /etc/conf.d/libmaxminddb

set -e

[ -z "$MAXMINDDB_FILES"       ] && MAXMINDDB_FILES="GeoLite2-City.mmdb"
[ -z "$MAXMINDDB_URL"         ] && MAXMINDDB_URL="https://download.maxmind.com/app/geoip_download"
[ -z "$MAXMINDDB_LIBDIR"      ] && MAXMINDDB_LIBDIR="/var/lib/libmaxminddb"
[ -z "$MAXMINDDB_LICENSE_KEY" ] && { echo "No MaxMind license key found; exiting. Please enter your license key into /etc/conf.d/libmaxminddb"; exit 1; }

clean_up() {
	[ -n "$TMPDIR" ] && rm -rf "$TMPDIR"
}
trap clean_up EXIT SIGTERM SIGINT SIGQUIT

TMPDIR="$(mktemp -d)"
for filename in $MAXMINDDB_FILES; do
	EDITION_ID=$(echo "${filename}" | sed 's/\.mmdb$//')
	curl --silent "${MAXMINDDB_URL}?edition_id=${EDITION_ID}&license_key=${MAXMINDDB_LICENSE_KEY}&suffix=tar.gz" -o "$TMPDIR/${filename}.tar.gz"
	tar xf "$TMPDIR/${filename}.tar.gz" -C "$TMPDIR" --strip-components=1
	mv "$TMPDIR/$filename" "$MAXMINDDB_LIBDIR"
done
exit 0
